﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PetaPoco
{
    /// <summary>
    /// 内部工具类
    /// </summary>
    internal static class Utils
    {
        private static readonly Dictionary<Type, Type> ToStringableNumericTypes;

        static Utils()
        {
            var toStringableNumericTypes = new List<Type>();
            toStringableNumericTypes.Add(typeof(byte));
            toStringableNumericTypes.Add(typeof(sbyte));
            toStringableNumericTypes.Add(typeof(short));
            toStringableNumericTypes.Add(typeof(ushort));
            toStringableNumericTypes.Add(typeof(int));
            toStringableNumericTypes.Add(typeof(uint));
            toStringableNumericTypes.Add(typeof(long));
            toStringableNumericTypes.Add(typeof(ulong));
            ToStringableNumericTypes = toStringableNumericTypes.ToDictionary(a => a, a => a);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsToStringableNumericType(Type type)
        {
            type = GetUnderlyingType(type);
            return ToStringableNumericTypes.ContainsKey(type);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Type GetUnderlyingType(this Type type)
        {
            if (!IsNullable(type, out var underlyingType))
                underlyingType = type;

            return underlyingType;
        }

        /// <summary>
        /// 是否允许为空判断
        /// </summary>
        /// <param name="type"></param>
        /// <param name="underlyingType"></param>
        /// <returns></returns>
        public static bool IsNullable(this Type type, out Type underlyingType)
        {
            underlyingType = Nullable.GetUnderlyingType(type);
            return underlyingType != null;
        }
    }
}
